2
2
.
.
1
1
1
1
.
.
1
1
0
0
F
F
r
r
o
o
m
m
J
J
S
S
O
O
N
N
-
-
@
@
J
J
s
s
o
o
n
n
F
F
o
o
r
r
m
m
a
a
t
t
I
I
n
n
f
f
o
o
[
[
G
G
]
]
[
[
R
R
]
]
This tutorial shows how to use @JsonFormat to specify Date Format of JSON Property.
That way Date can be properly loaded from JSON Property into DTO Property.
In this tutorial JSON Property birthday 25.02.2021 is converted into PersonDTO Property in LocalDate Format 2021-02-25.
@JsonFormat Annotation can be used to
Annotate public Properties (when public Properties are used for Deserialization in absence of Constructor)
Annotate Constructor Parameters (when Constructor is used for Deserialization)
Syntax
@JsonFormat(pattern="dd.MM.yyyy") //Define which date format is used by JSON Property: dd.mm.yyyy 25.02.2021
public LocalDate birthday; //It will be converted to LocalDate format: yyyy-mm-dd 2021-02-25
Application Schema [Results]
Spring Boot Starters
GROUP
DEPENDENCY
DESCRIPTION
Web
Spring Web
Enables: @Controller @RequestMapping, Tomcat Server
MyController
PersonDTO
POSTMAN
P
P
r
r
o
o
c
c
e
e
d
d
u
u
r
r
e
e
Create Project: bootspring_http_requestbody (add Spring Boot Starters from the table)
Create Package: DTO (inside main package)
Create Class: PersonDTO.java (inside package controllers)
Create Package: controllers (inside main package)
Create Class: MyController.java (inside package controllers)
PersonDTO.java
package com.ivoronline.springboot_dto_jsonproperty.DTO;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.time.LocalDate;
public class PersonDTO {
public String name;
//DEFINE WHICH DATE FORMAT IS USED BY JSON PROPERTY: dd.MM.yyyy 25.02.2021
//IT WILL BE CONVERTED TO LOCALDATE FORMAT: yyyy-MM-dd 2021-02-25
@JsonFormat(pattern="dd.MM.yyyy")
public LocalDate birthday;
}
MyController.java
import java.time.LocalDate;
@Controller
public class MyController {
@ResponseBody
@RequestMapping("/AddPerson")
public String addPerson(@RequestBody PersonDTO personDTO) {
//GET DATA FROM PersonDTO
String name = personDTO.name;
LocalDate birthday = personDTO.birthday;
//RETURN SOMETHING
return name + " is born on " + birthday;
}
}
R
R
e
e
s
s
u
u
l
l
t
t
s
s
Start Postman
POST
http://localhost:8080/AddPerson
Headers (add Key-Value)
Content-Type: application/json
Body (option: raw)
{
"name" : "John",
"birthday" : "25.02.2021"
}
Postman
HTTP Response Body
John is born on 2021-02-25
Application Structure
pomx.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>